Telegram Group & Telegram Channel
Тонкости STL, которые часто вылетают в продакшн:

1. Инвалидирование итераторов
При vector::erase все итераторы от позиции удаления до end() становятся «битые». Чтобы безопасно отфильтровать и удалить элементы, пользуйтесь erase–remove идиомой:


auto it = std::remove_if(v.begin(), v.end(), [](int x){ return x < 0; });
v.erase(it, v.end());


remove_if сдвигает «хвост» вперёд, но не меняет размер контейнера.

2. reserve vs resize

* v.reserve(n) выделяет память, но не создаёт объектов → size() не меняется, можно безопасно push_back.
* v.resize(n) создаёт n элементов, инициализированных значениями по умолчанию.

3. Производительность std::distance
На random-access итераторах (например, vector) это O(1), а на bidirectional или forward (например, list) — O(n). Для списков используйте size() (C++11+) или считайте вручную в критичных местах.

4. emplace_back vs push_back
При сложных типах emplace_back может избежать лишнего копирования:


v.emplace_back(ctor_arg1, ctor_arg2);
// vs
v.push_back(MyType(ctor_arg1, ctor_arg2));


5. Памятка про компараторы
В set или map ваш компаратор должен задавать строгий-уровень-менее (operator<): если comp(a,b)==true, то comp(b,a) обязан быть false. Иначе — UB.

Быстро, без воды, но с пользой — проверяйте эти моменты в своём коде!

➡️ @cpp_geek



tg-me.com/cpp_geek/321
Create:
Last Update:

Тонкости STL, которые часто вылетают в продакшн:

1. Инвалидирование итераторов
При vector::erase все итераторы от позиции удаления до end() становятся «битые». Чтобы безопасно отфильтровать и удалить элементы, пользуйтесь erase–remove идиомой:


auto it = std::remove_if(v.begin(), v.end(), [](int x){ return x < 0; });
v.erase(it, v.end());


remove_if сдвигает «хвост» вперёд, но не меняет размер контейнера.

2. reserve vs resize

* v.reserve(n) выделяет память, но не создаёт объектов → size() не меняется, можно безопасно push_back.
* v.resize(n) создаёт n элементов, инициализированных значениями по умолчанию.

3. Производительность std::distance
На random-access итераторах (например, vector) это O(1), а на bidirectional или forward (например, list) — O(n). Для списков используйте size() (C++11+) или считайте вручную в критичных местах.

4. emplace_back vs push_back
При сложных типах emplace_back может избежать лишнего копирования:


v.emplace_back(ctor_arg1, ctor_arg2);
// vs
v.push_back(MyType(ctor_arg1, ctor_arg2));


5. Памятка про компараторы
В set или map ваш компаратор должен задавать строгий-уровень-менее (operator<): если comp(a,b)==true, то comp(b,a) обязан быть false. Иначе — UB.

Быстро, без воды, но с пользой — проверяйте эти моменты в своём коде!

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/321

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

Among the actives, Ascendas REIT sank 0.64 percent, while CapitaLand Integrated Commercial Trust plummeted 1.42 percent, City Developments plunged 1.12 percent, Dairy Farm International tumbled 0.86 percent, DBS Group skidded 0.68 percent, Genting Singapore retreated 0.67 percent, Hongkong Land climbed 1.30 percent, Mapletree Commercial Trust lost 0.47 percent, Mapletree Logistics Trust tanked 0.95 percent, Oversea-Chinese Banking Corporation dropped 0.61 percent, SATS rose 0.24 percent, SembCorp Industries shed 0.54 percent, Singapore Airlines surrendered 0.79 percent, Singapore Exchange slid 0.30 percent, Singapore Press Holdings declined 1.03 percent, Singapore Technologies Engineering dipped 0.26 percent, SingTel advanced 0.81 percent, United Overseas Bank fell 0.39 percent, Wilmar International eased 0.24 percent, Yangzijiang Shipbuilding jumped 1.42 percent and Keppel Corp, Thai Beverage, CapitaLand and Comfort DelGro were unchanged.

C geek from it


Telegram C++ geek
FROM USA